package com.ljf.weixin;

import com.ljf.framework.security.LjfSecurityManager;
import com.ljf.framework.security.token.LjfTokenManager;
import com.ljf.framework.util.LjfHttpUtil;

import java.util.HashMap;

/**
 * 说明：
 *
 * @Auther: lijinfeng
 * @Date: 2024/5/21
 */
public class WeiXinManager {

    /**
     * 微信配置 Bean
     */
    private volatile static WeiXinConfig weChatConfig;

    public static WeiXinConfig getConfig() {
        if (weChatConfig == null) {
            synchronized (WeiXinManager.class) {
                if (weChatConfig == null) {
                    setConfig(new WeiXinConfig());
                }
            }
        }
        return weChatConfig;
    }

    public static void setConfig(WeiXinConfig config) {
        WeiXinManager.weChatConfig = config;
    }

    private volatile static WeiXinHandler weiXinHandler;

    public static WeiXinHandler getWeiXinHandler() {
        if (weiXinHandler == null) {
            synchronized (WeiXinManager.class) {
                if (weiXinHandler == null) {
                    setWeiXinHandler(new WeiXinHandler());
                }
            }
        }
        return weiXinHandler;
    }

    public static void setWeiXinHandler(WeiXinHandler weiXinHandler) {
        WeiXinManager.weiXinHandler = weiXinHandler;
    }


    /**
     * 通过定义枚举来扩展请求方法
     *
     * @param urlEnum
     * @param params
     * @return
     * @throws Exception
     */
    public static String doRequest(WeiXinUrlEnum urlEnum, HashMap<String, String> params) {
        String result = "";
        if ("GET".equals(urlEnum.getMethod())) {
            result = LjfHttpUtil.doGet(urlEnum.getUrl(), params);
        }
        if ("POST".equals(urlEnum.getMethod())) {
            result = LjfHttpUtil.doPost(urlEnum.getUrl(), params);
        }

        return result;

    }

    /**
     * 微信登录
     * @param openId
     * @param phoneNum
     * @param sessionKey
     * @return
     */
    public static String doLogin(String openId, Long phoneNum, String sessionKey) {
        Long userId = WeiXinManager.getWeiXinHandler().checkWeiXinUserHandler.apply(openId, phoneNum);
        LjfSecurityManager.login(userId);
        return LjfTokenManager.getTokenValue();
    }
}
